import mongoose = require('mongoose');
import q = require('bluebird');

mongoose.Promise = q;

declare module 'mongoose' {
    type Promise<T> = q<T>;
}

import DBLog = require("../model/OperatorRecord");

//-----------------

//================
import WebPageBase from "./WebPageBase";
import User = require("../model/UserInfo");
import CommonFunc from '../middleware/CommonFunc';
import fs = require('fs');
import WebConstant from '../common/WebConstant';
interface AjaxDataProvider{
    [key:string]:Function;
}

class AjaxDataProvider extends WebPageBase{
    public login(req:any):q<object>{
        let ipaddr = CommonFunc.getClientIp(req);
        if(!req.body){
            return this.makeErrorReturn("错误的请求",ipaddr);
        }
        var data = { username:req.body.username,password:req.body.password};
        let me = this;
        let username = data.username;
        let password = data.password;
        if(!username || !password){
            return this.makeErrorReturn("错误的参数",ipaddr);
        }
        let regPwd = new RegExp("^[A-Z0-9a-z]{6,}$");
        let regUser = new RegExp("^[A-Z0-9a-z\u4e00-\u9fa5]{1,}$");
        if(!regUser.test(username)){
            return this.makeErrorReturn("用户名不符合规则",ipaddr);
        }
        if(!regPwd.test(password)){
            return this.makeErrorReturn("密码不符合规则",ipaddr);
        }
        let promise = User.MODEL.findOne({"username":username,"password":password}).exec();

        return promise.then((ret:mongoose.Document | null)=>{
            if(ret && ret.toObject()["username"] == username){
                this.addLogToDB(true, "", ipaddr, username);
                if(req.session){
                    req.session.user = data;
                }
                return {"error":"", "success":true};
            }
            let msg = "用户名或者密码错误";
            this.addLogToDB(false, msg, ipaddr, username);
            return {"error":msg, "success":false};
        });
    }
    public addfolder(req:any):q<object>{
        let parent = req.body.parent;
        let dir:string = req.body.dirname;
        let me = this;
        return new q((okFunc, failFunc)=>{
            let currentUser = req.session && req.session.user && req.session.user.username;
            let defaultPath = CommonFunc.getRootUserPath(currentUser);
            try{
                if(!me.checkFolderName(dir)){
                    okFunc({"success":false, "error":"文件夹名称含有特殊字符"});
                    return;
                }
                if("temp" == dir.toLowerCase()){
                    okFunc({"success":false, "error":"文件夹名称不能使用temp"});
                    return;
                }
                //console.log(defaultPath,"|", parent,"|", dir);
                if(fs.existsSync(defaultPath + parent)){
                    fs.mkdirSync(defaultPath + parent + "/" + dir);   
                    
                    okFunc({"success":true});
                }
                else{
                    okFunc({"success":false, "error":"上一级文件夹不存在"});
                }
            }
            catch(ex){
                console.log("新建文件夹错误", ex);
                okFunc({"success":false, "error":"(异常)操作磁盘错误"});
            }
        });
        
    }
    public deletefile(req:any):q<object>{
        let path:string = req.body.path;
        let isdir = req.body.isdir;
        
        let me = this;
        return new q((okFunc, failFunc)=>{
            let currentUser = req.session && req.session.user && req.session.user.username;
            let uploadPath = WebConstant.UPLOAD_PATH;
            let strDesc = isdir ? " 文件夹" : "文件";
            try{
                if("admin" != currentUser){
                    okFunc({"success":false, "error":"Admin才允许删除操作"});
                    return;
                }
                path = uploadPath + path;
                if(fs.existsSync(path)){
                     
                    if(isdir == "true"){
                       me.removeDir(path); 
                    }
                    else{
                        
                        fs.unlinkSync(path);
                    }
                    okFunc({"success":true});
                }
                else{
                    
                    okFunc({"success":false, "error":strDesc+"不存在"});
                }
            }
            catch(ex){
                console.log("删除"+strDesc+"错误", ex);
                okFunc({"success":false, "error":"(异常)操作磁盘错误"});
            }
        });
    }
    private makeErrorReturn(msg:string, ipaddr:string):q<object>{
        this.addLogToDB(false, msg, ipaddr, "");

        return new q((resolve,reject)=>{
            resolve({"error":msg, "success":false});
        });
    }

    private addLogToDB(success:boolean, msg:string, ipaddr:string, user:string):void{
        let log = new DBLog.MODEL({
            recorddate:new Date(),
            username:user,
            ipaddr:ipaddr,	  
            description:msg,
            success:success
        }).save();      
    }

    private checkFolderName(name:string){
        let regCheck = new RegExp("^[A-Z0-9a-z\u4e00-\u9fa5-_]{1,}$");
        return regCheck.test(name);
    }

    private removeDir(path:string):boolean{
        try{
            let files = fs.readdirSync(path);
            if(files.length <= 0){
                fs.rmdirSync(path);
                return true;
            }
            for(let i = 0; i < files.length; i++){
                let filename = path+"/"+files[i];
                let stats = fs.lstatSync(filename);
                if(stats.isDirectory()){
                    this.removeDir(filename);
                }
                else if(stats.isFile){
                    fs.unlinkSync(filename);
                }
            }

            fs.rmdirSync(path);
            return true;
        }
        catch(ex){
            console.log("删除文件夹错误", ex);
            return false;
        }
        return true;
    }
}

export default AjaxDataProvider;